<template>
  <el-card class="box-card">
    <div class="news_header">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane :label="`${item.label}（${item.num}）`" :name="item.name" v-for="item in tabsList" :key="item.label"></el-tab-pane>
      </el-tabs>
      <MainSearchForm ref="supplierFormRef" :formList="formList" :formValue="formValue" @formReset="formChange" @formSearch="formChange"></MainSearchForm>
      <el-button size="mini" @click="openWaringPopup">设置预警值</el-button>
      <el-button size="mini" class="add-btn" v-if="waringDays">{{ waringDays }}天</el-button>
    </div>
    <div class="main_table mg-t-20" style="min-height: 600px">
      <MainTable
        ref="residuesTable"
        :loading="listLoading"
        :columns="columns"
        :tableData="tableData"
        showSelection
        :tree-props="{children: 'health_certificate_list', hasChildren: 'hasChildren'}"
      >
        <template #expand>
          <el-table-column type="expand" class-name="main_hei">
            <template #header>
                <div style="cursor: pointer">
                  <i @click="expandALL" class="expand-all" :class="isExpand ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
                </div>
              </template>
            <template slot-scope="props">
              <el-table
                :data="props.row.health_certificate_list"
                class="child-table"
                fit
                :highlight-current-row="false"
              >
                <el-table-column label width="40" align="right" />
                <el-table-column label="健康证编号" prop="no" />
                <el-table-column label="健康证名称" prop="real_name" />
                <el-table-column label="状态" prop="warn_status">
                  <template slot-scope="scope">
                    <span :style="{ color: filterStatus(scope.row.warn_status, 2) }">{{ filterStatus(scope.row.warn_status, 1) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="到期时间" prop="valid_date" />
                <el-table-column label="健康证" prop="photo">
                  <template slot-scope="scope">
                  <el-image :src="scope.row.photo" style="width: 60px" :preview-src-list="[scope.row.photo]"></el-image>
                </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
        </template>
        <template v-slot:warn_status="{ row }">
          <span :style="{ color: row.warn_status ? '#F56C6C' : '' }">{{ row.warn_status ? '异常' : '正常' }}</span>
        </template>
      </MainTable>
    </div>

    <div class="pagination-right mg-t-20">
      <MainPagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout=" ->,total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </MainPagination>
    </div>
    <MainDialog
      title="设置预警值"
      :showDialog="warningVisible"
      width="480px"
      @close="handleClose">
      <template v-slot:content>
        <el-form :model="waringForm" :rules="rules" label-position="right" label-width="100px" ref="warningFormRef" class="warning-form">
          <el-form-item label="距预警值：" prop="days">
            <el-input v-model="waringForm.days" placeholder="请输入天数" @input="handleInput"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template v-slot:footer>
        <div class="main-dialog-btn align-right">
          <el-button type="success" class="add-btn" @click="handleClose">取消</el-button>
          <el-button type="primary" class="submit" @click="submitExamine('warningFormRef')">确定</el-button>
        </div>
      </template>
    </MainDialog>
  </el-card>
</template>

<script>
import { getStaffWarnList, getStaffWarnSetDay, getStaffWarnTotal } from '@/api/residues/index'
import MainTable from '@/components/MainTable/table.vue'
import { indexData } from '../MockData'
const { columns, formList, formValue, tabsList, tableData } = indexData
export default {
  name: "news",
  components: {
    MainTable
  },
  data() {
    return {
      formList,
      formValue,
      tabsList,
      tableData,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      // 勾选的数据
      multipleSelection: [],
      // 新闻日期
      listLoading: false,
      columns,
      activeName: 'all',
      warningVisible: false,
      waringForm: {
        days: ''
      },
      rules: {
        days: [
          { required: true, message: '天数不能为空', trigger: 'blur' },
        ]
      },
      waringDays: '',  //  预警天数
      isExpand: false
    };
  },
  activated() {
    this.getData();
    this.getTabsNum();
  },
  methods: {
    //  表单搜索
    formChange() {
      this.currentPage = 1
      this.pageSize = 20
      this.getData()
    },
    getTabsNum() {
      getStaffWarnTotal({}).then(res => {
        if(res.errcode == 0) {
          this.tabsList.forEach(el => {
            el.num = res.data[el.key]
          })
        }
      })
    },
    getData() {
      this.listLoading = true;
      let data = {
        page: this.currentPage,
        page_size: this.pageSize,
        ...this.formValue,
        status: this.activeName === 'all' ? '' : this.activeName
      };
      getStaffWarnList(data).then(
        (res) => {
          this.listLoading = false;
          this.tableData = res.data.list.map(el => {
            return {
              ...el,
              hasChildren: Boolean(el.health_certificate_list.length)
            }
          });
          this.total = res.data.total;
          this.waringDays = res.data.warn_days;
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 勾选的数据
    handleSelectionChange(val) {
      console.log("val", val);
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getData();
    },
    handleClick() {
      this.$refs.supplierFormRef.getFormRefs().resetFields();
      this.formChange()
    },
    openWaringPopup() {
      this.warningVisible = true
      if(this.waringDays) this.waringForm.days = this.waringDays
    },
    handleClose() {
      this.warningVisible = false
      this.$refs.warningFormRef.resetFields()
    },
    submitExamine(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          getStaffWarnSetDay({ ...this.waringForm }).then(res => {
            if(res.errcode == 0) {
              this.$message.success('设置成功')
              this.waringDays = this.waringForm.days
              this.handleClose()
              this.getData()
            }else {
              this.$message.error(res.msg)
            }
          })
        } else {
          return false;
        }
      });
    },
    //  限制只能输入正整数
    handleInput(value) {
      // 替换所有非数字字符
      const reg = /\D/g;
      this.waringForm.days = value.replace(reg, '');
      // 如果输入的数字以0开头，除了0本身外，其他以0开头的数字都替换为''
      if (this.waringForm.days !== '' && this.waringForm.days[0] === '0') {
        this.waringForm.days = this.waringForm.days.replace(/^0/, '');
      }
    },
    filterStatus(status, type) {
      const statusObj = {
        0: {
          text: '正常',
          color: ''
        },
        1: {
          text: '过期',
          color: '#909399'
        },
        2: {
          text: '临期',
          color: '#F56C6C'
        },
      }
      return type === 1 ? statusObj[status].text : statusObj[status].color
    },
    //  展开全部
    expandALL() {
      this.isExpand = !this.isExpand;
      this.tableData.forEach((el) => {
        this.$refs.residuesTable.getTableRef().toggleRowExpansion(el, this.isExpand);
      });
    }
  },
  created() {
  },
};
</script>
<style lang="scss" scoped>
@import '../index.scss';
.warning-form {
  /deep/.el-form-item {
    margin-bottom: 0;
  }
}
.expand-all {
  font-size: 15px;
  font-weight: bold;
  padding-left: 6px;
}
</style>
